<template>
  <div>
    <div class="search">
      <input class="search-input" type="text" placeholder="输入城市或拼音" v-model="keyword">
    </div>
    <div class="search-list" ref="search" v-show="keyword">
      <ul>
        <li class="item-list border-bottom" v-for="(item,index) of list" :key="index"
         @click="handleCityClick(item)"
         >
         {{item}}
         </li>
        <li class="item-list border-bottom" v-show="hasNoData">没有找到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (item) {
      // this.$store.commit('changeCity', item)
      this.changeCity(item)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let key in this.cities) {
          this.cities[key].forEach((value) => {
            let pos1 = value.spell.indexOf(this.keyword)
            let pos2 = value.name.indexOf(this.keyword)
            if (pos1 > -1 || pos2 > -1) {
              result.push(value.name)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>
<style lang="scss" scoped>
@import '~styles/variables' ;
.search{
  height: .72rem;
  padding: 0 .1rem;
  background: $baseColor;
  .search-input{
    width: 100%;
    height: .62rem;
    font-size: .32rem;
    text-align: center;
    border-radius: .06rem;
    color: #666;
    padding: 0 .32rem;
    box-sizing: border-box;
  }
}
.search-list{
  position: absolute;
  top: 1.56rem;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
  background: #eee;
  z-index: 999;
  ul{
    .item-list{
      line-height: 0.56rem;
      background: #fff;
      padding-left: 0.2rem;
    }
  }
}
</style>
